package cn.anyubao.blog.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author huqilang
 */
public final class FieldUtils {
    private static final Logger log = LoggerFactory.getLogger(FieldUtils.class);
    private static final Map<Class<?>, List<Field>> CLASS_FIELD_MAP = new ConcurrentHashMap();

    private FieldUtils() {
    }

    public static List<Field> getFields(Class<?> clazz) {
        List<Field> fieldList = (List)CLASS_FIELD_MAP.get(clazz);
        if (fieldList == null) {
            fieldList = new ArrayList();
            setFields(clazz, (List)fieldList);
            CLASS_FIELD_MAP.put(clazz, fieldList);
        }

        return (List)fieldList;
    }

    public static Object getFieldVal(Object entity, Field field) {
        Object retVal = null;

        try {
            ReflectionUtils.makeAccessible(field);
            retVal = field.get(entity);
        } catch (Exception var4) {
            log.warn("获取属性值失败：" + entity.getClass().getSimpleName() + "." + field.getName(), var4);
        }

        return retVal;
    }

    private static void setFields(Class<?> clazz, List<Field> fieldList) {
        if (clazz != Object.class) {
            Field[] fields = clazz.getDeclaredFields();
            if (fields != null && fields.length > 0) {
                fieldList.addAll((Collection) Stream.of(fields).filter((field) -> {
                    return !Modifier.isStatic(field.getModifiers());
                }).collect(Collectors.toList()));
            }

            setFields(clazz.getSuperclass(), fieldList);
        }
    }

}
